package com.chexiehui.jc.ui.activity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aries.ui.view.radius.RadiusTextView;
import com.aries.ui.widget.action.sheet.UIActionSheetDialog;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.bumptech.glide.Glide;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpActivity;
import com.chexiehui.jc.entity.AddressEntity;
import com.chexiehui.jc.entity.MerchantAuthInfo;
import com.chexiehui.jc.entity.MerchantAuthParamsInfo;
import com.chexiehui.jc.event.MerchantAuthSaveEvent;
import com.chexiehui.jc.mvp.mine.CarMerchantAuthCovenant;
import com.chexiehui.jc.mvp.mine.CarMerchantAuthPresenter;
import com.chexiehui.jc.utils.AliossUtil;
import com.chexiehui.jc.utils.AppCommonUtil;
import com.chexiehui.jc.utils.BundleBuilder;
import com.chexiehui.jc.utils.GlideEngine;
import com.chexiehui.jc.utils.GlideUtil;
import com.chexiehui.jc.utils.NoDoubleClickUtils;
import com.chexiehui.jc.widget.CustomXPopupImageLoader;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.style.PictureWindowAnimationStyle;
import com.luck.picture.lib.tools.LocalMediaUtils;
import com.lxj.xpopup.XPopup;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;
import me.zhouzhuo.zzimagebox.ZzImageBox;

/**
 * 车商认证
 */
public class CarMerchantAuthActivity extends BaseMvpActivity<CarMerchantAuthPresenter> implements CarMerchantAuthCovenant.View {
    @BindView(R.id.tv_auth_tip)
    TextView tvAuthTip;
    @BindView(R.id.tv_shop_company_type)
    TextView tvShopCompanyType;
    @BindView(R.id.et_shop_company_name)
    EditText etShopCompanyName;
    @BindView(R.id.et_shop_name)
    EditText etShopName;
    @BindView(R.id.et_shop_address)
    EditText etShopAddress;
    @BindView(R.id.iv_choose_address)
    ImageView ivChooseAddress;
    @BindView(R.id.tv_shop_head_title)
    TextView tvShopHeadTitle;
    @BindView(R.id.tv_look_head_demo)
    TextView tvLookHeadDemo;
    @BindView(R.id.tv_shop_head_tip)
    TextView tvShopHeadTip;
    @BindView(R.id.zz_head_box)
    ZzImageBox zzHeadBox;
    @BindView(R.id.tv_shop_license_title)
    TextView tvShopLicenseTitle;
    @BindView(R.id.tv_look_license_demo)
    TextView tvLookLicenseDemo;
    @BindView(R.id.tv_shop_license_tip)
    TextView tvShopLicenseTip;
    @BindView(R.id.iv_shop_license)
    ImageView ivShopLicense;
    @BindView(R.id.zz_environment_box)
    ZzImageBox zzEnvironmentBox;
    @BindView(R.id.rtv_save_submit)
    RadiusTextView rtvSaveSubmit;
    @BindView(R.id.tv_resume_reason)
    TextView tvResumeReason;
    @BindView(R.id.ll_resume_reason)
    LinearLayout llResumeReason;

    private MerchantAuthInfo merchantAuthInfo;
    private MerchantAuthParamsInfo authParamsInfo;

    @Override
    protected void beforeSetView() {
        merchantAuthInfo = new MerchantAuthInfo();
        merchantAuthInfo.setStatus(3);
        authParamsInfo = new MerchantAuthParamsInfo();
    }

    @Override
    protected void setTitleBar() {
        titleBar.setTitleMainText("车商认证");
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_car_merchant_auth;
    }

    @Override
    protected void initView(Bundle var1) {
        zzHeadBox.setOnlineImageLoader((iv, url) -> {
            Glide.with(mContext).load(url)
                    .placeholder(R.drawable.iv_default)
                    .error(R.drawable.iv_default)
                    .into(iv);
        });
        zzEnvironmentBox.setOnlineImageLoader((iv, url) -> {
            Glide.with(mContext).load(url)
                    .placeholder(R.drawable.iv_default)
                    .error(R.drawable.iv_default)
                    .into(iv);
        });
        zzHeadBox.setOnImageClickListener(new ZzImageBox.OnImageClickListener() {
            @Override
            public void onImageClick(int position, String filePath, ImageView iv) {

            }

            @Override
            public void onDeleteClick(int position, String filePath) {
                if(merchantAuthInfo.getStatus() == 0){
                    return;
                }
                zzHeadBox.removeImage(position);
                merchantAuthInfo.imgsRemoveUrl(position, filePath);
            }

            @Override
            public void onAddClick() {
                if(merchantAuthInfo.getStatus() == 0){
                    return;
                }
                applyPhotoPermission(300);
            }
        });
        zzEnvironmentBox.setOnImageClickListener(new ZzImageBox.OnImageClickListener() {
            @Override
            public void onImageClick(int position, String filePath, ImageView iv) {

            }

            @Override
            public void onDeleteClick(int position, String filePath) {
                if(merchantAuthInfo.getStatus() == 0){
                    return;
                }
                zzEnvironmentBox.removeImage(position);
                merchantAuthInfo.envirImgsRemoveUrl(position, filePath);
            }

            @Override
            public void onAddClick() {
                if(merchantAuthInfo.getStatus() == 0){
                    return;
                }
                applyPhotoPermission(500);
            }
        });
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) ivShopLicense.getLayoutParams();
        lp.width = (ScreenUtils.getScreenWidth() - SizeUtils.dp2px(35)) / 4;
        lp.height = lp.width;
        setSubmitButtonStatus();
        ivShopLicense.setLayoutParams(lp);
        mvpPresenter.getAuthParams();
        mvpPresenter.getMerchantAuthInfo();
    }

    private void setMerchantDataInfo(){
        tvShopCompanyType.setText(merchantAuthInfo.getCompanyType());
        etShopCompanyName.setText(merchantAuthInfo.getCompanyName());
        etShopName.setText(merchantAuthInfo.getStoreName());
        etShopAddress.setText(merchantAuthInfo.getStoreAdress());
        if(!StringUtils.isTrimEmpty(merchantAuthInfo.getImgs())){
            List<String> imgs = AppCommonUtil.stringToSplitList(merchantAuthInfo.getImgs());
            for (int i = 0; i < imgs.size(); i++) {
                zzHeadBox.addImage(AliossUtil.getEndPointFileUrl(imgs.get(i)));
            }
        }
        if(!StringUtils.isTrimEmpty(merchantAuthInfo.getEnvirImgs())){
            List<String> imgs = AppCommonUtil.stringToSplitList(merchantAuthInfo.getEnvirImgs());
            for (int i = 0; i < imgs.size(); i++) {
                zzEnvironmentBox.addImage(AliossUtil.getEndPointFileUrl(imgs.get(i)));
            }
        }
        if(!StringUtils.isTrimEmpty(merchantAuthInfo.getAuthFiles())){
            GlideUtil.loadImageViewCrop(mContext, AliossUtil.getEndPointFileUrl(merchantAuthInfo.getAuthFiles()), ivShopLicense,
                    R.mipmap.ic_upload_add, R.mipmap.ic_upload_add);
        }
    }

    @OnClick({R.id.tv_shop_company_type, R.id.iv_choose_address, R.id.tv_look_head_demo,
            R.id.tv_look_license_demo, R.id.tv_look_environment_demo,
            R.id.iv_shop_license, R.id.rtv_save_submit})
    public void onViewClicked(View view) {
        if(merchantAuthInfo.getStatus() == 0){
            return;
        }
        if(NoDoubleClickUtils.isDoubleClick()){
            return;
        }
        switch (view.getId()) {
            case R.id.tv_shop_company_type:
                showChooseTypeDialog();
                break;
            case R.id.iv_choose_address:
                if(getMerchantAuthInfo().getLat() > 0 && getMerchantAuthInfo().getLon() > 0){
                    AddressEntity mAddressEntity = new AddressEntity(getMerchantAuthInfo().getStoreAdress());
                    mAddressEntity.setLat(getMerchantAuthInfo().getLat());
                    mAddressEntity.setLat(getMerchantAuthInfo().getLon());
                    startActivityForResult(MapChooseActivity.class, 100, new BundleBuilder()
                            .putSerializable("entity", mAddressEntity)
                            .create());
                }else{
                    startActivityForResult(MapChooseActivity.class, 100, new BundleBuilder()
                            .putSerializable("entity", null)
                            .create());
                }
                break;
            case R.id.tv_look_head_demo:
                if(authParamsInfo != null && !StringUtils.isTrimEmpty(authParamsInfo.getExamples1())){
                    try {
                        new XPopup.Builder(mContext)
                                .asImageViewer(null, authParamsInfo.getExamples1(), new CustomXPopupImageLoader())
                                .show();
                    }catch (Exception ignored){}
                }else{
                    showToast("暂无示例图片");
                }
                break;
            case R.id.tv_look_license_demo:
                if(authParamsInfo != null && !StringUtils.isTrimEmpty(authParamsInfo.getExamples2())){
                    try {
                        new XPopup.Builder(mContext)
                                .asImageViewer(null, authParamsInfo.getExamples2(), new CustomXPopupImageLoader())
                                .show();
                    }catch (Exception ignored){}
                }else{
                    showToast("暂无示例图片");
                }
                break;
            case R.id.tv_look_environment_demo:
                if(authParamsInfo != null && !StringUtils.isTrimEmpty(authParamsInfo.getExamples3())){
                    try {
                        new XPopup.Builder(mContext)
                                .asImageViewer(null, authParamsInfo.getExamples3(), new CustomXPopupImageLoader())
                                .show();
                    }catch (Exception ignored){}
                }else{
                    showToast("暂无示例图片");
                }
                break;
            case R.id.iv_shop_license:
                applyPhotoPermission(400);
                break;
            case R.id.rtv_save_submit:
                merchantAuthInfo.setCompanyName(etShopCompanyName.getText().toString().trim());
                merchantAuthInfo.setStoreName(etShopName.getText().toString().trim());
                merchantAuthInfo.setStoreAdress(etShopAddress.getText().toString().trim());
                mvpPresenter.save();
                break;
        }
    }

    private void applyPhotoPermission(final int code) {
        AndPermission.with(this)
                .permission(Permission.CAMERA, Permission.STORAGE)
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                        PictureWindowAnimationStyle windowAnimationStyle = new PictureWindowAnimationStyle();
                        windowAnimationStyle.ofAllAnimation(R.anim.picture_anim_up_in, R.anim.picture_anim_down_out);
                        // 进入相册 以下是例子：不需要的api可以不写
                        PictureSelector.create(mContext)
                                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                                .loadImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                                .theme(R.style.picture_QQ_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style v2.3.3后 建议使用setPictureStyle()动态方式
                                .setPictureWindowAnimationStyle(windowAnimationStyle)// 自定义相册启动退出动画
                                .imageSpanCount(4)// 每行显示个数
                                .isReturnEmpty(false)// 未选择数据时点击按钮是否可以返回
                                .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 设置相册Activity方向，不设置默认使用系统
                                .isOriginalImageControl(false)// 是否显示原图控制按钮，如果设置为true则用户可以自由选择是否使用原图，压缩、裁剪功能将会失效
                                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                                .isSingleDirectReturn(true)// 单选模式下是否直接返回，PictureConfig.SINGLE模式下有效
                                .previewImage(true)// 是否可预览图片
                                .isCamera(true)// 是否显示拍照按钮
                                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                                .enableCrop(false)// 是否裁剪
                                .cropWH(95, 66)
                                .withAspectRatio(95, 66)
                                .showCropFrame(true)
                                .freeStyleCropEnabled(false)
                                .scaleEnabled(false)
                                .showCropGrid(false)
                                .showCropFrame(true)
                                .compress(true)// 是否压缩
                                .compressQuality(90)// 图片压缩后输出质量 0~ 100
                                .synOrAsy(false)//同步false或异步true 压缩 默认同步
                                .queryMaxFileSize(20)// 只查多少M以内的图片、视频、音频  单位M
                                .isGif(false)// 是否显示gif图片
                                .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                                .minimumCompressSize(100)// 小于100kb的图片不压缩
                                .recordVideoSecond(60)//录制视频秒数 默认60s
                                .forResult(code);//结果回调onActivityResult code*/
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                        if (AndPermission.hasAlwaysDeniedPermission(mContext, deniedPermissions)) {
                            AndPermission.defaultSettingDialog(mContext, Constants.REQUEST_CODE_CARAME).show();
                        } else {
                            showToast(getStringSource(R.string.app_name) + "需要您授权打开相机和相册的权限");
                        }
                    }
                })
                .requestCode(Constants.REQUEST_CODE_CARAME)
                .rationale((requestCode, rationale) -> AndPermission.rationaleDialog(mContext, rationale).show()).start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 100:
                if (resultCode == RESULT_OK) {
                    AddressEntity a = (AddressEntity) data.getSerializableExtra("address");
                    if (a != null) {
                        getMerchantAuthInfo().setStoreAdress(a.getAddressAll());
                        etShopAddress.setText(getMerchantAuthInfo().getStoreAdress());
                        etShopAddress.setSelection(etShopAddress.getText().length());
                    }
                }
            case 300: {
                List<LocalMedia> selectedPhotoList = PictureSelector.obtainMultipleResult(data);
                if (selectedPhotoList.size() > 0) {
                    String path = LocalMediaUtils.getLocalPath(selectedPhotoList.get(0));
                    mvpPresenter.uploadShopImage(path);
                }
            }
            break;
            case 500: {
                List<LocalMedia> selectedPhotoList = PictureSelector.obtainMultipleResult(data);
                if (selectedPhotoList.size() > 0) {
                    String path = LocalMediaUtils.getLocalPath(selectedPhotoList.get(0));
                    mvpPresenter.uploadShopEnvironment(path);
                }
            }
            break;
            case 400: {
                List<LocalMedia> selectedPhotoList = PictureSelector.obtainMultipleResult(data);
                if (selectedPhotoList.size() > 0) {
                    String path = LocalMediaUtils.getLocalPath(selectedPhotoList.get(0));
                    mvpPresenter.uploadLicenseImage(path);
                }
            }
            break;
        }
    }

    private void showChooseTypeDialog() {
        if(authParamsInfo.getCompanyType().size() > 0){
            UIActionSheetDialog dialog = new UIActionSheetDialog.ListIOSBuilder(mContext)
                    .addItems(authParamsInfo.getCompanyType().toArray(new String[authParamsInfo.getCompanyType().size()]))
                    .setTitle("选择公司类型")
                    .setOnItemClickListener((dialog1, itemView, position) -> {
                        dialog1.dismiss();
                        merchantAuthInfo.setCompanyType(authParamsInfo.getCompanyType().get(position));
                        tvShopCompanyType.setText(merchantAuthInfo.getCompanyType());
                    })
                    .create();
            dialog.show();
        }else{
            showToast("暂无公司类型数据");
        }
    }

    @Override
    protected CarMerchantAuthPresenter createPresenter() {
        return new CarMerchantAuthPresenter(this);
    }

    @Override
    public void onGetAuthParamsSuccess(BaseModel<MerchantAuthParamsInfo> successResult) {
        authParamsInfo = successResult.getData();
    }

    @Override
    public void onGetAuthParamsFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public void onGetMerchantAuthInfoSuccess(BaseModel<MerchantAuthInfo> successResult) {
        if(successResult.getData() != null){
            merchantAuthInfo = successResult.getData();
            setMerchantDataInfo();
        }else{
            merchantAuthInfo.setStatus(3);
        }
        setSubmitButtonStatus();
    }

    private void setSubmitButtonStatus() {
        llResumeReason.setVisibility(View.GONE);
        if(merchantAuthInfo.getStatus() == 0){
            rtvSaveSubmit.setText("审核中");
            rtvSaveSubmit.setEnabled(false);
            etShopAddress.setEnabled(false);
            etShopCompanyName.setEnabled(false);
            etShopName.setEnabled(false);
        } else if(merchantAuthInfo.getStatus() == 1){
            rtvSaveSubmit.setText("重新认证");
            rtvSaveSubmit.setEnabled(true);
            etShopAddress.setEnabled(true);
            etShopCompanyName.setEnabled(true);
            etShopName.setEnabled(true);
        } else if(merchantAuthInfo.getStatus() == 2){
            rtvSaveSubmit.setText("重新提交");
            rtvSaveSubmit.setEnabled(true);
            etShopAddress.setEnabled(true);
            etShopCompanyName.setEnabled(true);
            etShopName.setEnabled(true);
            llResumeReason.setVisibility(View.VISIBLE);
            tvResumeReason.setText(merchantAuthInfo.getOpinion());
        }else if(merchantAuthInfo.getStatus() == 3){
            rtvSaveSubmit.setText("提交审核");
            rtvSaveSubmit.setEnabled(true);
            etShopAddress.setEnabled(true);
            etShopCompanyName.setEnabled(true);
            etShopName.setEnabled(true);
        }else{
            rtvSaveSubmit.setText("审核中");
            rtvSaveSubmit.setEnabled(false);
            etShopAddress.setEnabled(false);
            etShopCompanyName.setEnabled(false);
            etShopName.setEnabled(false);
        }
    }

    @Override
    public void onGetMerchantAuthInfoFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public void onUploadShopImageSuccess(BaseModel<String> successResult) {
        zzHeadBox.addImage(AliossUtil.getEndPointFileUrl(successResult.getData()));
        merchantAuthInfo.imgsAddUrl(successResult.getData());
    }

    @Override
    public void onUploadShopImageFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public void onUploadShopEnvironmentSuccess(BaseModel<String> successResult) {
        zzEnvironmentBox.addImage(AliossUtil.getEndPointFileUrl(successResult.getData()));
        merchantAuthInfo.envirImgsAddUrl(successResult.getData());
    }

    @Override
    public void onUploadShopEnvironmentFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public void onUploadLicenseImageSuccess(BaseModel<String> successResult) {
        merchantAuthInfo.setAuthFiles(successResult.getData());
        GlideUtil.loadImageViewCrop(mContext, AliossUtil.getEndPointFileUrl(merchantAuthInfo.getAuthFiles()), ivShopLicense,
                R.mipmap.ic_upload_add, R.mipmap.ic_upload_add);
    }

    @Override
    public void onUploadLicenseImageFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public void onSaveSuccess(BaseModel<Object> successResult) {
        EventBus.getDefault().post(new MerchantAuthSaveEvent());
        SubmitSuccessTipActivity.start(CarMerchantAuthActivity.this,
                "您的信息已提交成功,请保持电话畅通,客服可能会与您联系确认信息",
                "我知道了",
                0);
        finish();
    }

    @Override
    public void onSaveFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public MerchantAuthInfo getMerchantAuthInfo() {
        return merchantAuthInfo;
    }
}
